﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace benefit.Controllers
{
    public class OperatorController : Controller
    {
        public ActionResult Create()
        {
            BenefitHelper.DB.DBManager db = new BenefitHelper.DB.DBManager();
            var query = new BenefitHelper.Sys.Groups().GetGroups(db);
            ViewBag.groups = query;
            db.Dispose();
            if (!string.IsNullOrEmpty(Request.QueryString["type"]))
            {
                ViewBag.iid = Request.QueryString["type"];
            }
            else
            {
                ViewBag.iid = "";
            }
            return View();
        }
        [HttpPost]
        public ActionResult Create(BenefitHelper.Sys.Operator oper)
        {
            BenefitHelper.DB.DBManager db = new BenefitHelper.DB.DBManager();
            oper.BatchId = new BenefitHelper.Sys.Batch().GetNewBatch();
            oper.IsDeleted = false;
            if (string.IsNullOrEmpty(oper.Sex))
            {
                oper.Sex = "男";
            }
            int userid = oper.AddOperator(db);


            int usergroupid = Convert.ToInt32(Request.Form["usergroup"]);
            BenefitHelper.Sys.GroupOperators go = new BenefitHelper.Sys.GroupOperators();
            go.GroupId = usergroupid;
            go.OperatorId = userid;
            db.GroupOperators.Add(go);
            db.SaveChanges();

            List<BenefitHelper.Sys.GroupOperators> ops = go.GetGroupOperators(usergroupid, db);

            if (!string.IsNullOrEmpty(Request.Form["ismaster"]) || ops.Count == 1)//指定对方为组长或者第一个加入的组员 就会被认定为组长
            {
                BenefitHelper.Sys.GroupMaster gm = new BenefitHelper.Sys.GroupMaster();
                gm.GroupId = usergroupid;
                gm.MasterId = userid;
                if (db.GroupMaster.Where(a => a.MasterId == userid).Where(a => a.GroupId == usergroupid).Count() == 0)
                {
                    db.GroupMaster.Add(gm);
                    db.SaveChanges();
                }
            }



            db.Dispose();

            if (!string.IsNullOrEmpty(Request.Form["iid"]))
            {
                return RedirectToAction("AddNewOperator", "Init", new { type = "1" });
            }
            else
            {
                return RedirectToAction("AddNewOperator", "Init");
            }

        }

        public ActionResult Edit(int id)
        {
            BenefitHelper.DB.DBManager db = new BenefitHelper.DB.DBManager();
            var query = db.Operators.Find(id);

            List<BenefitHelper.Sys.Groups> groups = new BenefitHelper.Sys.Groups().GetGroups(db);
            ViewBag.groups = groups;

            List<BenefitHelper.Sys.GroupOperators> masters = new List<BenefitHelper.Sys.GroupOperators>();
            masters = new BenefitHelper.Sys.GroupOperators().GetList(db);
            foreach (BenefitHelper.Sys.GroupOperators master in masters)
            {
                if (id == master.OperatorId)
                {
                    ViewBag.GroupId = master.GroupId;
                    break;
                }
            }

            //  var query=db.GroupMaster.Where(a=>a.MasterId==id).Where()

            db.Dispose();

            if (!string.IsNullOrEmpty(Request.QueryString["type"]))
            {
                ViewBag.iid = Request.QueryString["type"];
            }
            else
            {
                ViewBag.iid = "";
            }

            return View(query);
        }

        [HttpPost]
        public ActionResult Edit(BenefitHelper.Sys.Operator oper)
        {
            BenefitHelper.DB.DBManager db = new BenefitHelper.DB.DBManager();
            var query = db.Operators.Find(oper.Id);
            query.Email = oper.Email;
            query.Password = oper.Password;
            query.Phone = oper.Phone;
            query.Sex = oper.Sex;
            query.UName = oper.UName;
            query.Username = oper.Username;
            db.SaveChanges();


            var query2 = db.GroupOperators.Where(a => a.OperatorId == oper.Id).ToList();
            foreach (BenefitHelper.Sys.GroupOperators op in query2)
            {
                db.GroupOperators.Remove(op);
            }
            db.SaveChanges();

            int usergroupid = Convert.ToInt32(Request.Form["usergroup"]);
            BenefitHelper.Sys.GroupOperators go = new BenefitHelper.Sys.GroupOperators();
            go.GroupId = usergroupid;
            go.OperatorId = oper.Id;
            db.GroupOperators.Add(go);
            db.SaveChanges();
            if (!string.IsNullOrEmpty(Request.Form["ismaster"]))
            {
                BenefitHelper.Sys.GroupMaster gm = new BenefitHelper.Sys.GroupMaster();
                gm.GroupId = usergroupid;
                gm.MasterId = oper.Id;
                if (db.GroupMaster.Where(a => a.MasterId == oper.Id).Where(a => a.GroupId == usergroupid).Count() == 0)
                {
                    db.GroupMaster.Add(gm);
                    db.SaveChanges();
                }
            }
            db.Dispose();

            if (!string.IsNullOrEmpty(Request.Form["iid"]))
            {
                return RedirectToAction("AddNewOperator", "Init", new { type = "1" });
            }
            else
            {
                return RedirectToAction("AddNewOperator", "Init");
            }


        }

        public ActionResult Delete(int id)
        {
            BenefitHelper.DB.DBManager db = new BenefitHelper.DB.DBManager();
            var query = db.Operators.Find(id);
            query.IsDeleted = true;
            db.SaveChanges();
            db.Dispose();

            if (!string.IsNullOrEmpty(Request.QueryString["type"]))
            {
                return RedirectToAction("AddNewOperator", "Init", new { type = "1" });
            }
            else
            {
                return RedirectToAction("AddNewOperator", "Init");
            }


        }

        public ActionResult CreateOperatorAccount(int id)
        {
            BenefitHelper.DB.DBManager db = new BenefitHelper.DB.DBManager();
            List<BenefitHelper.Data.ServerData.T_Account> unSavedServerAccount = new List<BenefitHelper.Data.ServerData.T_Account>();
            int connectionStringCount = System.Configuration.ConfigurationManager.ConnectionStrings.Count;
            for (int i = 0; i < connectionStringCount; i++)
            {
                string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings[i].ConnectionString;
                if (System.Configuration.ConfigurationManager.ConnectionStrings[i].ProviderName.Equals("System.Data.OracleClient"))
                {
                    Common.ADO.Tools.OracleHelper.connectionString = connectionString;
                    List<BenefitHelper.Data.ServerData.T_Account> accountList = new BenefitHelper.Data.ServerData.T_Account().GetList();
                    foreach (BenefitHelper.Data.ServerData.T_Account _account in accountList)
                    {
                        unSavedServerAccount.Add(_account);
                    }
                }
            }

            BenefitHelper.Data.ServerData.T_Account account = unSavedServerAccount.Where(a => a.Id == id).First();
            ViewBag.account = account;

            ViewBag.operators = db.Operators.ToList();
            db.Dispose();

            return View();
        }

        [HttpPost]
        public ActionResult CreateOperatorAccount()
        {
            BenefitHelper.DB.DBManager db = new BenefitHelper.DB.DBManager();
            BenefitHelper.Sys.Account account = new BenefitHelper.Sys.Account();
            List<BenefitHelper.Data.ServerData.T_Account> unSavedServerAccount = new List<BenefitHelper.Data.ServerData.T_Account>();
            int connectionStringCount = System.Configuration.ConfigurationManager.ConnectionStrings.Count;
            for (int i = 0; i < connectionStringCount; i++)
            {
                string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings[i].ConnectionString;
                if (System.Configuration.ConfigurationManager.ConnectionStrings[i].ProviderName.Equals("System.Data.OracleClient"))
                {
                    Common.ADO.Tools.OracleHelper.connectionString = connectionString;
                    List<BenefitHelper.Data.ServerData.T_Account> accountList = new BenefitHelper.Data.ServerData.T_Account().GetList();
                    foreach (BenefitHelper.Data.ServerData.T_Account _account in accountList)
                    {
                        unSavedServerAccount.Add(_account);
                    }
                }
            }

            BenefitHelper.Data.ServerData.T_Account aaa = new BenefitHelper.Data.ServerData.T_Account();
            aaa = unSavedServerAccount.Where(a => a.Id == Convert.ToInt32(Request.Form["Id"])).First();
            account.AccountName = aaa.LoginAccount;
            account.DeletedTime = DateTime.Now;
            account.IsDeleted = false;
            db.Accounts.Add(account);
            db.SaveChanges();


            BenefitHelper.Sys.OperatorAccount oa = new BenefitHelper.Sys.OperatorAccount();
            oa.OperatorId = Convert.ToInt32(Request.Form["operator"]);
            oa.AccountId = account.Id;
            db.OperatorAccount.Add(oa);
            db.SaveChanges();



            db.Dispose();
            return RedirectToAction("AddNewAccount", "Init");
        }
        /// <summary>
        /// 为账户设定操作员
        /// </summary>
        /// <param name="id">这个ID是Account的ID</param>
        /// <returns></returns>
        public ActionResult OperatorAccountEdit(int id)
        {
            BenefitHelper.DB.DBManager db = new BenefitHelper.DB.DBManager();
            ViewBag.operators = new BenefitHelper.Sys.Operator().GetUnDeletedOperators(db);
            var query = db.OperatorAccount.Where(a => a.AccountId == id);
            if (query.Count() > 0)
            {
                BenefitHelper.Sys.OperatorAccount oa = query.First();
                ViewBag.operatoraccount = oa;
            }

            BenefitHelper.Sys.Account account = db.Accounts.Find(id);
            ViewBag.account = account;

            db.Dispose();
            return View();
        }
        [HttpPost]
        public ActionResult OperatorAccountEdit()
        {
            BenefitHelper.DB.DBManager db = new BenefitHelper.DB.DBManager();
            int id = Convert.ToInt32(Request.Form["Id"]);
            if (id != -1)
            {
                var query = db.OperatorAccount.Find(id);
                query.OperatorId = Convert.ToInt32(Request.Form["operator"]);
            }
            else
            {
                int accountid = Convert.ToInt32(Request.Form["Accountid"]);
                int operatorid = Convert.ToInt32(Request.Form["operator"]);
                BenefitHelper.Sys.OperatorAccount oa = new BenefitHelper.Sys.OperatorAccount();
                oa.AccountId = accountid;
                oa.OperatorId = operatorid;
                db.OperatorAccount.Add(oa);
            }
            db.SaveChanges();

            db.Dispose();
            return RedirectToAction("AddNewAccount", "Init");
        }

        public ActionResult OperatorAccountDelete(int id)
        {
            BenefitHelper.DB.DBManager db = new BenefitHelper.DB.DBManager();
            var query = db.Accounts.Find(id);
            query.IsDeleted = true;
            db.SaveChanges();
            db.Dispose();
            return RedirectToAction("AddNewAccount", "Init");
        }
    }
}